﻿IF EXISTS (SELECT * FROM sysobjects WHERE type = 'P' AND name = 'roleDelete')
	BEGIN
		DROP  Procedure  roleDelete
	END
GO
-- =============================================
-- Author:		Ricardo
-- Create date: 04/03/2009
-- Description:	Deletes a role from the database
-- =============================================
CREATE PROCEDURE [dbo].[roleDelete] 
	@role_name VARCHAR(50),
	@app_id INT,
	@throw BIT
AS	
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
	DECLARE @role_id INT;

	SELECT @role_id = lit_rol_id
	FROM lit_rol
	WHERE lit_rol_nombre = @role_name 
	AND lit_aplicacion_id = @app_id;

	IF (@role_id IS NOT NULL) BEGIN
		IF EXISTS(	SELECT lit_rol_id 
					FROM lit_usuario_rol 
					WHERE lit_rol_id = @role_id ) BEGIN
			-- Hay usuarios asociados al rol
			IF (@throw = 1) BEGIN
				SELECT 0;
			END
			ELSE BEGIN
				DELETE FROM lit_usuario_rol WHERE lit_rol_id = @role_id;
				DELETE FROM lit_rol_privilegio WHERE lit_rol_id = @role_id;
				DELETE FROM lit_rol WHERE lit_rol_id = @role_id;	
				SELECT 1;
			END
						
		END
		ELSE BEGIN
			DELETE FROM lit_rol_privilegio WHERE lit_rol_id = @role_id;
			DELETE FROM lit_rol WHERE lit_rol_id = @role_id;	
			SELECT 1;
		END
	END
	ELSE BEGIN
		SELECT 1;
	END
END
GO